import React, { useState, useEffect } from 'react';
import { NavBar, Radio, Toast } from 'antd-mobile';
import { LeftOutline } from 'antd-mobile-icons';
import { useNavigate, useLocation } from 'react-router-dom';
import '../styles/confirmOrder.scss';

// 支付方式类型
type PaymentMethod = 'wechat' | 'alipay' | 'medical';

const ConfirmOrderPage: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>('wechat');

    // 检查是否是直接访问此页面（而不是从预约流程进入）
    const isDirectAccess = !location.state;

    // 如果是直接访问且没有上下文，可以选择重定向或显示提示
    useEffect(() => {
        if (isDirectAccess) {
            Toast.show({
                content: '请通过正常预约流程进入确认订单页面',
                afterClose: () => {
                    // 可以选择重定向到首页或预约首页
                    // navigate('/');
                }
            });
        }
    }, [isDirectAccess, navigate]);

    // 默认值
    const defaultValues = {
        doctor: { name: '张医生', title: '主任医师', department: '心内科', hospital: '协和医院' },
        selectedDate: { day: '周四', date: '2023-07-20' },
        selectedTime: '10:00',
        selectedPatient: { name: '张三', age: 35, gender: '男', relation: '本人' },
        diseaseDesc: '最近一个月经常感到胸闷、心慌，有时会伴随轻微胸痛，已经服用硝酸甘油但效果不理想'
    };

    // 从location.state获取预约信息
    const locationState = location.state as any;

    // 使用可选链和空值合并运算符确保安全获取数据
    const doctor = locationState?.doctor || defaultValues.doctor;
    const selectedDate = locationState?.selectedDate || defaultValues.selectedDate;
    const selectedTime = locationState?.selectedTime || defaultValues.selectedTime;
    const selectedPatient = locationState?.selectedPatient || defaultValues.selectedPatient;
    const diseaseDesc = locationState?.diseaseDesc || defaultValues.diseaseDesc;

    // 费用信息
    const feeInfo = {
        registrationFee: 150,
        serviceFee: 0,
        totalFee: 150
    };

    // 处理返回按钮点击
    const handleBack = () => {
        // 这里假设导航来自于患者选择页面，可能需要获取医生ID
        // 如果有location.state中有doctorId，则使用它
        const doctorId = locationState?.doctor?.id || '1';
        navigate(`/booking/patient/${doctorId}`);
    };

    // 处理支付方式选择
    const handlePaymentMethodChange = (method: PaymentMethod) => {
        setPaymentMethod(method);
    };

    // 处理立即支付按钮点击
    const handlePay = () => {
        // 生成随机订单号
        const generateOrderNumber = () => {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const random = Math.floor(Math.random() * 10000000).toString().padStart(7, '0');
            return `${year}${month}${day}${random}`;
        };

        // 模拟就诊地址
        const visitAddress = '北京市朝阳区物南园1号 协和医院门诊楼5层';

        Toast.show({
            icon: 'success',
            content: '支付成功',
            afterClose: () => {
                // 支付成功后跳转到支付成功页面
                navigate('/payment-success', {
                    state: {
                        doctor,
                        selectedDate,
                        selectedTime,
                        selectedPatient,
                        feeInfo,
                        orderNumber: generateOrderNumber(),
                        visitAddress
                    }
                });
            }
        });
    };

    return (
        <div className="confirm-order-page">
            {/* 顶部导航栏 */}
            <NavBar
                className="nav-bar"
                onBack={handleBack}
            >
                确认订单
            </NavBar>

            {/* 预约信息 */}
            <div className="order-section">
                <h2 className="section-title">预约信息</h2>
                <div className="doctor-info">
                    <div className="avatar">
                        <img src="/images/doctor-avatar.png" alt="医生头像" />
                    </div>
                    <div className="info">
                        <div className="name-title">
                            {doctor.name} · {doctor.title}
                        </div>
                        <div className="dept-hospital">
                            {doctor.department} · {doctor.hospital}
                        </div>
                        <div className="appointment-time">
                            {selectedDate.date} ({selectedDate.day}) {selectedTime}
                        </div>
                    </div>
                </div>

                {/* 就诊人信息 */}
                <div className="patient-info">
                    <div className="label">就诊人</div>
                    <div className="value">{selectedPatient.name} | {selectedPatient.age}岁 | {selectedPatient.gender}</div>
                </div>

                {/* 病情描述 */}
                <div className="disease-desc">
                    <div className="label">病情描述</div>
                    <div className="value">{diseaseDesc}</div>
                </div>
            </div>

            {/* 费用信息 */}
            <div className="fee-section">
                <h2 className="section-title">费用信息</h2>
                <div className="fee-item">
                    <div className="fee-label">挂号费</div>
                    <div className="fee-value">¥ {feeInfo.registrationFee.toFixed(2)}</div>
                </div>
                <div className="fee-item">
                    <div className="fee-label">平台服务费</div>
                    <div className="fee-value">¥ {feeInfo.serviceFee.toFixed(2)}</div>
                </div>
                <div className="fee-total">
                    <div className="fee-label">合计</div>
                    <div className="fee-value">¥ {feeInfo.totalFee.toFixed(2)}</div>
                </div>
            </div>

            {/* 支付方式 */}
            <div className="payment-section">
                <h2 className="section-title">支付方式</h2>
                <Radio.Group
                    value={paymentMethod}
                    onChange={(val) => handlePaymentMethodChange(val as PaymentMethod)}
                >
                    <div className="payment-method">
                        <div className="method-info">
                            <div className="method-icon wechat-icon"></div>
                            <div className="method-name">微信支付</div>
                        </div>
                        <Radio value="wechat" />
                    </div>
                    <div className="payment-method">
                        <div className="method-info">
                            <div className="method-icon alipay-icon"></div>
                            <div className="method-name">支付宝</div>
                        </div>
                        <Radio value="alipay" />
                    </div>
                    <div className="payment-method">
                        <div className="method-info">
                            <div className="method-icon medical-icon"></div>
                            <div className="method-name">医保支付</div>
                        </div>
                        <Radio value="medical" />
                    </div>
                </Radio.Group>
            </div>

            {/* 底部支付栏 */}
            <div className="payment-footer">
                <div className="total-fee">
                    实付款：
                    <span className="fee-amount">¥ {feeInfo.totalFee.toFixed(2)}</span>
                </div>
                <button className="pay-button" onClick={handlePay}>
                    立即支付
                </button>
            </div>
        </div>
    );
};

export default ConfirmOrderPage; 